package cn.xiaoxiang.basic.interceptor;

import cn.xiaoxiang.basic.annotation.PreAuthorize;
import cn.xiaoxiang.basic.jwt.JwtUtils;
import cn.xiaoxiang.basic.jwt.Payload;
import cn.xiaoxiang.basic.jwt.RsaUtils;
import cn.xiaoxiang.basic.jwt.UserInfo;
import cn.xiaoxiang.system.mapper.PermissionMapper;
import cn.xiaoxiang.user.domain.Logininfo;
import cn.xiaoxiang.user.domain.User;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 1. 去header中取token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)){
            // 如果token存在 去reids中查询
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
        //jwt

            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            if (null != userInfo.getLogininfo()){


                if(0==userInfo.getLogininfo().getType()){
                    //获取自定义注解
                    HandlerMethod handlerMethod= (HandlerMethod) handler;
                    PreAuthorize perAuth = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (null!=perAuth){
                        //请求方法上的sn
                        String persn = perAuth.sn();
                        //查询用户当前拥有的权限
//                        List<String> snList= permissionMapper.findByLogininId(userInfo.getLogininfo().getId());
                        List<String> snList= payload.getUserInfo().getPermissions();
                        if(!snList.contains(persn)){
                            //当前用户没有的权限
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 重置过期时间
//                redisTemplate.expire(token,30, TimeUnit.MINUTES)
                return true;
            }
        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;

    }
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
//        // 3.1.设置编码字符集
//        response.setCharacterEncoding("UTF-8");
//        // 3.2.设置响应参数类型为JSON
//        response.setContentType("application/json;charset=UTF-8");
//        // 1. 去header中取token
//        String token = request.getHeader("token");
//        if (StringUtils.isNotBlank(token)){
//            // 如果token存在 去reids中查询
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
//
//            if (null != logininfo){
//
//
//                if(0==logininfo.getType()){
//                    //获取自定义注解
//                    HandlerMethod handlerMethod= (HandlerMethod) handler;
//                    PreAuthorize perAuth = handlerMethod.getMethodAnnotation(PreAuthorize.class);
//                    if (null!=perAuth){
//                        //请求方法上的sn
//                        String persn = perAuth.sn();
//                        //查询用户当前拥有的权限
//                        List<String> snList= permissionMapper.findByLogininId(logininfo.getId());
//                        if(!snList.contains(persn)){
//                            //当前用户没有的权限
//                            PrintWriter writer = response.getWriter();
//                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
//                            // 3.4.刷新、关流
//                            writer.flush();
//                            writer.close();
//                        }
//                    }
//
//                }
//
//                // 重置过期时间
//                redisTemplate.expire(token,30, TimeUnit.MINUTES);
//                return true;
//            }
//        }
//
//        // 3.3.获取到打印流,并设置响应数据
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
//        // 3.4.刷新、关流
//        writer.flush();
//        writer.close();
//        return false;
//
//    }
}
